package com.atguigu.gulimall.product.exception;

import com.atguigu.common.exception.BizCodeEnum;
import com.atguigu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestControllerAdvice( "com.atguigu.gulimall.product.controller")
public class GulimallExceptionHandle {
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R  validatorExceptHandle(MethodArgumentNotValidException e){
        Map<String,String> res = new HashMap<>();
        BindingResult bindingResult = e.getBindingResult();
        bindingResult.getFieldErrors().forEach(item->{
            res.put(item.getField(),item.getDefaultMessage());
        });
        log.error("异常类型：{}",e.getClass());
        return R.error(BizCodeEnum.VAILD_EXCEPTION.getCode(),BizCodeEnum.VAILD_EXCEPTION.getMsg()).put("data",res);
    }
    @ExceptionHandler(Throwable.class)
    public R  validatorExceptHandle(Throwable e){
        log.error("系统未知异常",e);
        return R.error(BizCodeEnum.UNKNOW_EXCEPTION.getCode(),BizCodeEnum.UNKNOW_EXCEPTION.getMsg());
    }
}
